//
//  RegisterViewController.m
//  Rabbit
//
//  Created by 阿帕 on 2018/11/14.
//  Copyright © 2018年 GCY. All rights reserved.
//

#import "RegisterViewController.h"
#import "CYWebViewViewController.h"
#import "ImageVerifyAlert.h"

@interface RegisterViewController ()
{
    BOOL _isAgree;//协议是否勾选
    BOOL _isCheckInvite;//邀请人信息是否校验
    NSString *_identityType;
}
@property (weak, nonatomic) IBOutlet UITextField *telTextField;
@property (weak, nonatomic) IBOutlet UITextField *codeTextField;
@property (weak, nonatomic) IBOutlet UITextField *yaoqingTextField;//邀请码
@property (weak, nonatomic) IBOutlet UIButton *sendCodeButton;
@property (weak, nonatomic) IBOutlet UIButton *serAgreeBtn;
@property (weak, nonatomic) IBOutlet UIButton *agreeBtn;
@property (weak, nonatomic) IBOutlet UITextField *passwordTextField;
@property (weak, nonatomic) IBOutlet UITextField *confPsdTextField;
@property (weak, nonatomic) IBOutlet UIButton *sijiBtn;
@property (weak, nonatomic) IBOutlet UILabel *cheduiBtn;
@property (weak, nonatomic) IBOutlet UIButton *registerButton;
@property (weak, nonatomic) IBOutlet UIImageView *phoneImageView;
@property (weak, nonatomic) IBOutlet UIImageView *codeImageView;
@property (weak, nonatomic) IBOutlet UIImageView *psdImageView;
@property (weak, nonatomic) IBOutlet UIImageView *psd2ImageView;
@property (weak, nonatomic) IBOutlet UIImageView *nicknameImageView;

@end

@implementation RegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [KNotificationCenter addObserver:self selector:@selector(backEvent) name:@"REGISTERBACKEVENT" object:nil];
    
    self.navigationItem.title = @"注册";
    
    _telTextField.textFieldType = CJTextFieldStringTypeNumber;
    _telTextField.maxLength = 11;
    
    _codeTextField.textFieldType = CJTextFieldStringTypeNumber;
    _codeTextField.maxLength = 6;
    
//    _passwordTextField.textFieldType = CJTextFieldStringTypePassword;
    _passwordTextField.maxLength = 18;
    
//    _confPsdTextField.textFieldType = CJTextFieldStringTypePassword;
    _confPsdTextField.maxLength = 18;
    
//    _yaoqingTextField.textFieldType = CJTextFieldStringTypeNone;
//    _yaoqingTextField.maxLength = 20;
    
    _isAgree = YES;
    _isCheckInvite = NO;//默认没有校验
    _identityType = @"0"; //默认身份是司机
    
    _telTextField.textColor = Dark_TextColor;
    _codeTextField.textColor = Dark_TextColor;
//    _yaoqingTextField.textColor = Dark_TextColor;
    _passwordTextField.textColor = Dark_TextColor;
    _confPsdTextField.textColor = Dark_TextColor;
    
    NSString *agreementStr = [NSString stringWithFormat:@"《%@司机端服务协议》", APP_PlatformName];
    NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:[@"同意" stringByAppendingString:agreementStr]];
    [attString addAttribute:(NSString*)NSForegroundColorAttributeName value:Light_TextColor range:[_serAgreeBtn.titleLabel.text rangeOfString:@"同意"]];
    [attString addAttribute:(NSString*)NSForegroundColorAttributeName value:Theme_ColorValue range:[_serAgreeBtn.titleLabel.text rangeOfString:agreementStr]];
    [_serAgreeBtn setAttributedTitle:attString forState:UIControlStateNormal];
    [_registerButton setBackgroundColor:Theme_ColorValue];
    [_sendCodeButton setBackgroundColor:Theme_ColorValue];
    _sendCodeButton.titleLabel.adjustsFontSizeToFitWidth = YES;
    
    cut(_registerButton, BTN_BORDER_RADIUS);
    
//    _phoneImageView.image = [[UIImage imageNamed:@"gcy_img_login_tel"] imageChangeColor:Theme_ColorValue];
//    _codeImageView.image = [[UIImage imageNamed:@"gcy_img_register_code"] imageChangeColor:Theme_ColorValue];
//    _psdImageView.image = [[UIImage imageNamed:@"gcy_img_login_password"] imageChangeColor:Theme_ColorValue];
//    _psd2ImageView.image = [[UIImage imageNamed:@"gcy_img_login_password"] imageChangeColor:Theme_ColorValue];
//    _nicknameImageView.image = [[UIImage imageNamed:@"gcy_img_register_nickname"] imageChangeColor:Theme_ColorValue];
    _sijiBtn.imageView.image = [[UIImage imageNamed:@"btn_siji_selected"] imageChangeColor:Theme_ColorValue];
    [_agreeBtn setImage:[image(@"gcy_img_home_business_select") imageChangeColor:Theme_ColorValue] forState:UIControlStateNormal];
}

- (void)dealloc {
    [KNotificationCenter removeObserver:self name:@"REGISTERBACKEVENT" object:nil];
}

- (void)backEvent {
    
    [self.navigationController popToRootViewControllerAnimated:YES];
    
    [KNotificationCenter postNotificationName:@"LoginDismissEvent" object:nil];
}

#pragma mark - 隐藏显示密码
- (IBAction)showOrHiddenPsdEvent:(UIButton *)sender {
    if (sender.selected) {
        [sender setImage:image(@"gcy_icon_close_eye") forState:UIControlStateNormal];
        _passwordTextField.secureTextEntry = YES;
        _confPsdTextField.secureTextEntry = YES;
        
    } else {
        [sender setImage:image(@"gcy_icon_open_eye") forState:UIControlStateNormal];
        _passwordTextField.secureTextEntry = NO;
        _confPsdTextField.secureTextEntry = NO;
        
    }
    sender.selected = !sender.selected;
}

#pragma mark - CheckInviterEventDelegate
- (void)CheckInviterBtnClick:(NSInteger)btnIndex {
    
    if (btnIndex == 300) {
        //取消
        _isCheckInvite = NO;
    }else {
        //确定
        _isCheckInvite = YES;//校验通过
    }
    
}
- (IBAction)sijiOrcheduiBtnClick:(UIButton *)sender {
    
    UIButton *leftBtn = [self.view viewWithTag:300];
    UIButton *rightBtn = [self.view viewWithTag:301];
    
    
    
    if (sender.tag == 300) {
        //是司机
        _identityType = @"0";
        
        [sender setImage:image(@"btn_siji_selected") forState:UIControlStateNormal];
        [rightBtn setImage:image(@"gcy_btn_siji_nomal") forState:UIControlStateNormal];
        
        [sender setImage:[[UIImage imageNamed:@"btn_siji_selected"] imageChangeColor:Theme_ColorValue] forState:UIControlStateNormal];
        
    } else {
        _identityType = @"1";
        [sender setImage:image(@"btn_siji_selected") forState:UIControlStateNormal];
        [leftBtn setImage:image(@"gcy_btn_siji_nomal") forState:UIControlStateNormal];
        
        [sender setImage:[[UIImage imageNamed:@"btn_siji_selected"] imageChangeColor:Theme_ColorValue] forState:UIControlStateNormal];
        
    }
    
    
}


- (IBAction)buttonTypeClick:(UIButton *)sender {
    WEAKSELF
    if (sender.tag == 100) {
        
        //注册
        if (_telTextField.text.length != 11) {
            [XSInfoView showInfo:@"手机号必须是11位" onView:self.view];
            return;
        }
        if (_codeTextField.text.length != 6) {
            [XSInfoView showInfo:@"验证码必须是6位" onView:self.view];
            return;
        }
        if (_passwordTextField.text.length > 20 || _confPsdTextField.text.length > 20) {
            [XSInfoView showInfo:@"密码最长为20位" onView:self.view];
            return;
        }
//        if (_yaoqingTextField.text.length > 15) {
//            [XSInfoView showInfo:@"输入的姓名过长" onView:self.view];
//            return;
//        }
        if (![_passwordTextField.text isEqual:_confPsdTextField.text]) {
            [XSInfoView showInfo:@"两次输入的密码不一致" onView:self.view];
            return;
        }
        
        if ([DCSpeedy isBlankString:_telTextField.text] == NO && [DCSpeedy isBlankString:_codeTextField.text] == NO && [DCSpeedy isBlankString:_passwordTextField.text] == NO && [DCSpeedy isBlankString:_confPsdTextField.text] == NO) {
            
            if (_isAgree == NO) {
                [XSInfoView showInfo:@"请阅读并同意注册协议" onView:self.view];
                return;
            }
            
            //发起注册
            NSDictionary *params = @{
                @"partyType": _identityType, //用户类型，0 司机 1 车队物流公司 2发货人 3发货企业
                @"phone": _telTextField.text,
//                @"name": _yaoqingTextField.text,//这个暂作为昵称
//                @"upass": _passwordTextField.text,
                @"upass": [DCSpeedy base64:_passwordTextField.text], // 加密
                @"verifyCode": _codeTextField.text,
                @"branchCode": [UserDefaultUtil valueForKey:BranchCode],
            };
            [HTTPManager postNetworkRequest:CJStringWithFormat(@"%@%@",[NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl],PARTY_REGISTER) withParameter:params withVC:self netName:@"注册" success:^(id response, NSString *msg) {
                
                [XSInfoView showInfo:@"注册成功" onView:weakSelf.view];
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
                    [weakSelf.navigationController popViewControllerAnimated:YES];
                });
                
            } failure:^(NSInteger code, NSString *msg) {
                
            }];
            
        }else{
            [XSInfoView showInfo:@"信息为空请检查" onView:self.view];
        }
        
    }else if (sender.tag == 101) {
        
        
        
    }else if (sender.tag == 102){
        
        //发送验证码
        if (_telTextField.text.length != 11) {
            [XSInfoView showInfo:@"请填写正确的手机号码" onView:self.view];
        } else {
            
            [self.view endEditing:YES];
            
            //判断手机号是否被注册
            [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl], PARTY_VALIDPHONE) withParameter:@{@"phone": _telTextField.text} withVC:self netName:@"注册手机号是否被注册" success:^(id response, NSString *msg) {
                
                ImageVerifyAlert *imageVerifyAlert = [[ImageVerifyAlert alloc] initWithFrame:CGRectMake(0, 0, ScreenW-30, 210)];
                imageVerifyAlert.backgroundColor = [UIColor whiteColor];
                cut(imageVerifyAlert, 5);
                imageVerifyAlert.phoneNum = _telTextField.text;
                [[GlobalPopUpTool sharedInstance] popUpWithView:imageVerifyAlert withViewController:self withAnimation:YES withCanTapBgCancel:YES];
                imageVerifyAlert.sendImgCodeBlock = ^(BOOL isConfirm, NSString * _Nonnull code) {
                    if (isConfirm) {
                        [self getCodeRequest:code];
                    } else {
                        [[GlobalPopUpTool sharedInstance] removePopUpView];
                    }
                };
                
            } failure:^(NSInteger code, NSString *msg) {
                
            }];
            
        }
    }
}

- (void)getCodeRequest:(NSString *)code {
    WEAKSELF
    NSDictionary *params = @{@"partyGroupCode": [UserDefaultUtil valueForKey:BranchCode] == nil ? Default_BranchCode : [UserDefaultUtil valueForKey:BranchCode],
                             @"phone":CJStringWithFormat(@"%@",_telTextField.text),
                             @"imageCode": code,
                             @"time": [DCSpeedy getCurrentTimes],
    };
    
    [HTTPManager postNetworkRequest:[NSString stringWithFormat:@"%@%@",[NSString stringWithFormat:@"%@/ntocc-tps-api",[ReAddressDynamic shared].baseUrl],SMS_SENDVERIFICATIONCODE] withParameter:params withVC:self netName:@"获取验证码" success:^(id response, NSString *msg) {
        
        [XSInfoView showInfo:msg onView:weakSelf.view];
        
        [[GlobalPopUpTool sharedInstance] removePopUpView];
        
        [weakSelf theCountdown];
        
    } failure:^(NSInteger code, NSString *msg) {
        
        [[GlobalPopUpTool sharedInstance] removePopUpView];
        
    }];
}

- (IBAction)registerAgreementBtnClick:(UIButton *)sender {
    
    if (sender.tag == 200) {
        if (_isAgree == YES) {
            _isAgree = NO;
            [_agreeBtn setImage:image(@"gcy_img_home_business_nomal") forState:UIControlStateNormal];
        }else{
            _isAgree = YES;
            [_agreeBtn setImage:[image(@"gcy_img_home_business_select") imageChangeColor:Theme_ColorValue] forState:UIControlStateNormal];
        }
    }else {
        //协议
        
        CYWebViewViewController *webVC = [[CYWebViewViewController alloc] init];
        webVC.titleString = @"注册协议";
        webVC.urlString = CJStringWithFormat(@"%@/agreement/agreement.html?agreementType=2", BasicDomainURL);
        webVC.state = 1;
        [self.navigationController pushViewController:webVC animated:YES];
    }
}

- (void)theCountdown{
    
    UIButton *button = [self.view viewWithTag:102];
    
    __block int timeout= 59; //倒计时时间
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    
    dispatch_source_set_event_handler(_timer, ^{
        
        if(timeout<=0){ //倒计时结束，关闭
            
            dispatch_source_cancel(_timer);
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置界面的按钮显示 根据自己需求设置
                
                [button setTitle:@"验证码" forState:UIControlStateNormal];
                [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                [button setBackgroundColor:Theme_ColorValue];
                button.userInteractionEnabled = YES;
            });
            
        }else{
            
            //            int minutes = timeout / 60;
            
            int seconds = timeout % 60;
            
            NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置界面的按钮显示 根据自己需求设置
                
                [UIView beginAnimations:nil context:nil];
                
                [UIView setAnimationDuration:0];
                
                [button setTitle:[NSString stringWithFormat:@"%@ S",strTime] forState:UIControlStateNormal];
                //                [button setBackgroundColor:[UIColor whiteColor]];
                [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                //                cutBorder(_sendCodeBtn, .5f, @"999999");
                //                [button setBackgroundColor:[UIColor clearColor]];
                [UIView commitAnimations];
                
                button.userInteractionEnabled = NO;
                
            });
            
            timeout--;
            
        }
        
    });
    
    dispatch_resume(_timer);
}

@end

//                NSArray *vcArray = weakSelf.navigationController.viewControllers;       //利用堆栈的思想定义数组
//                for(UIViewController *vc in vcArray)
//                {
//                    if ([vc isKindOfClass:[MyViewController class]]) {
//                        [self.navigationController popToViewController:vc animated:YES];
//                    }
//                }
